package com.whfc.emp.helmet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.DeviceType;
import com.whfc.common.third.helmet.HelmetProperties;
import com.whfc.common.third.map.MapApi;
import com.whfc.common.third.map.MapLoc;
import com.whfc.common.util.JSONUtil;
import com.whfc.emp.cncit.entity.CncitUpMsgS;
import com.whfc.emp.entity.AppDeviceCardLog;
import com.whfc.emp.enums.PosState;
import com.whfc.emp.manager.AppEmpDataManager;
import com.whfc.emp.service.AppHelmetService;
import com.whfc.hdc.dto.AppDeviceDTO;
import com.whfc.hdc.service.AppDeviceService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

import static com.whfc.emp.helmet.ZbznVideoApi.*;


@Component
public class ZbznVideoParse {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ZbznVideoApi zbznVideoApi;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @DubboReference(interfaceClass = AppHelmetService.class, version = "1.0.0")
    private AppHelmetService appHelmetService;

    @DubboReference(interfaceClass = AppDeviceService.class, version = "1.0.0")
    private AppDeviceService appDeviceService;

    public static String mock_data_get_active_devices = "{\"cmd\":\"ma_get_active_devices\",\"status\":true,\"msg\":\"获取成功\",\"data\":[{\"user_info\":{\"user_id\":\"136419\",\"bt_scanner\":null,\"ca_ver\":\"rd_aqm6811-q0.mp1-L5.0Ah-PV1-6811rd-m6811runde-user-svn7246-v1.2.3-20240223_1126\",\"device_id\":\"866652022192928\",\"nh3\":null,\"h2s\":null,\"mobile\":\"17818881888\",\"sim\":\"89861124248088042879\",\"c_time\":\"1758164238\",\"app_last_login_time\":\"0\",\"ca_last_login_time\":\"1758189844\",\"user_name\":\"17818881888\",\"real_name\":\"17818881888\",\"user_img\":\"https:\\/\\/mg.runde.pro\\/public\\/images\\/default.jpeg\",\"department\":\"866652022192927\",\"role\":\"866652022192927\",\"f_id\":\"0\",\"cap_type\":\"2\",\"b1\":\"\",\"b2\":\"\",\"sos_height\":\"10000.00\",\"tk\":\"2\",\"nearvolt\":\"2\",\"health\":\"2\",\"pressure\":\"2\",\"account_id\":\"607\",\"w_id\":null,\"acc_list\":\"607,17791,18569\",\"c_user_id\":\"18569\",\"gas_volt\":\"0\",\"new_low\":\"0\",\"uwb_device_id\":\"\",\"rtmp_open\":\"0\",\"voice_pkg\":null,\"fb_id\":null,\"min_o2\":\"19.5\",\"max_o2\":\"23.5\",\"watch\":\"\",\"local_record\":\"1\",\"last_count_online_time\":\"1758189844\",\"watch_mac\":\"\",\"co\":\"10.0\",\"app_version\":\"M6811_64\",\"min_temp\":null,\"max_temp\":null,\"max_heartbeat\":null,\"min_heartbeat\":null,\"shrink\":null,\"diastolic\":null,\"video_pre\":null,\"push_sos_url\":null,\"electrostatic\":null,\"headset\":\"\",\"upload_video_num\":\"2\",\"notuploaded_video_count\":\"0\",\"privacy_switch\":\"0\",\"g_id\":\"26780\",\"boot_broadcast\":\"0\",\"video_call_type\":\"3\",\"ca_report_time\":\"0\",\"ch4\":null,\"gas_collection\":\"{\\\"ch4\\\":0,\\\"co2\\\":0,\\\"h2s\\\":0,\\\"nh3\\\":0,\\\"so2\\\":0,\\\"voc\\\":0,\\\"ph3\\\":0,\\\"no2\\\":0,\\\"o3\\\":0,\\\"cl2\\\":0,\\\"hcl\\\":0,\\\"hf\\\":0,\\\"ch2o\\\":0,\\\"sf6\\\":0,\\\"no\\\":0,\\\"h2\\\":0}\",\"location\":\"\",\"obstacle_distance_up\":\"\",\"obstacle_distance_rear\":\"\",\"light_value\":\"0\",\"sip_id\":0},\"location_info\":{\"act\":\"ca_report_location\",\"altitude\":\"null\",\"bat_l\":\"89\",\"bat_v\":\"3914\",\"body_info\":\"\",\"body_simple_info\":\"\",\"bt_signal_info\":\"{\\\"dataList\\\":[{\\\"mac\\\":\\\"44:48:FF:59:F5:27\\\",\\\"name\\\":\\\"U-ACF526\\\",\\\"rssi\\\":-94,\\\"updateTime\\\":1758189970829}]}\",\"c_accuracy\":\"0.0\",\"c_speed\":\"0.0\",\"c_startcount\":\"0\",\"c_trust\":\"0\",\"charging\":\"1\",\"gas_data\":\"\",\"gps\":\"0\",\"gps_level\":\"-1\",\"hanger_a_bat\":\"-1\",\"hanger_a_status\":\"-1\",\"hanger_b_bat\":\"-1\",\"hanger_b_status\":\"-1\",\"in_use\":\"1\",\"is_weared\":\"1\",\"lights_switch\":\"0\",\"mic_switch\":\"0\",\"net_strenth\":\"4\",\"net_type\":\"1\",\"notuploaded_video_count\":\"0\",\"online_type\":\"2\",\"oxygen_data\":\"\",\"phoneNumber\":\"89861124248088042879\",\"rail_status\":\"0\",\"record_switch\":\"false\",\"sim_data_num\":\"139\",\"sim_status\":\"2\",\"stepCount\":241,\"stepCountTime\":1758189974266,\"tcard_status\":\"1\",\"tempdata\":\"mtktsbtsmdpa--14623\",\"user_id\":\"136419\",\"x_point\":\"41.80419297960069\",\"y_point\":\"123.33912543402778\",\"ctime\":1758189975,\"Altitude\":\"0.0\",\"cap_type\":\"2\"}}],\"msg_code\":\"GetSucc\"}";

    public static String mock_data_push_sos = "{\"cmd\":\"server_push_sos\",\"status\":true,\"msg\":\"获取成功\",\"data\":{\"user_id\":\"136419\",\"device_id\":\"866652022192927\",\"ca_ver\":\"rd_aqm6811-q0.mp1-L5.0Ah-PV1-6811rd-m6811runde-user-svn7246-v1.2.3-20240223_1126\",\"mobile\":\"17818881888\",\"sim\":\"89861124248088042879\",\"pwd\":\"123456\",\"c_time\":\"1758164238\",\"app_last_login_time\":\"0\",\"ca_last_login_time\":\"1758189844\",\"user_name\":\"17818881888\",\"real_name\":\"17818881888\",\"user_img\":\"https:\\/\\/mg.runde.pro\\/public\\/images\\/default.jpeg\",\"department\":\"866652022192927\",\"role\":\"866652022192927\",\"f_id\":\"0\",\"cap_type\":\"2\",\"b1\":\"\",\"b2\":\"\",\"sos_height\":\"10000.00\",\"tk\":\"2\",\"nearvolt\":\"2\",\"health\":\"2\",\"pressure\":\"2\",\"account_id\":\"607\",\"w_id\":null,\"acc_list\":\"607,17791,18569\",\"c_user_id\":\"18569\",\"gas_volt\":\"0\",\"new_low\":\"0\",\"uwb_device_id\":\"\",\"rtmp_open\":\"0\",\"voice_pkg\":null,\"fb_id\":null,\"min_o2\":\"19.5\",\"max_o2\":\"23.5\",\"watch\":\"\",\"local_record\":\"1\",\"last_count_online_time\":\"1758189905\",\"watch_mac\":\"\",\"co\":\"10.0\",\"app_version\":\"M6811_64\",\"min_temp\":null,\"max_temp\":null,\"max_heartbeat\":null,\"min_heartbeat\":null,\"shrink\":null,\"diastolic\":null,\"video_pre\":null,\"push_sos_url\":null,\"electrostatic\":null,\"headset\":\"\",\"upload_video_num\":\"2\",\"notuploaded_video_count\":\"0\",\"privacy_switch\":\"0\",\"boot_broadcast\":\"0\",\"gas_mac\":\"\",\"check_upgrade\":null,\"new_app_id\":null,\"check_system_upgrade\":null,\"new_system_app_id\":null,\"floor\":\"0\",\"bt_strength\":\"0\",\"bt_scanner\":null,\"nh3\":null,\"h2s\":null,\"video_call_type\":\"3\",\"ca_report_time\":\"0\",\"ch4\":null,\"hook_mac\":\"\",\"room_id\":null,\"gas_collection\":\"{\\\"ch4\\\":0,\\\"co2\\\":0,\\\"h2s\\\":0,\\\"nh3\\\":0,\\\"so2\\\":0,\\\"voc\\\":0,\\\"ph3\\\":0,\\\"no2\\\":0,\\\"o3\\\":0,\\\"cl2\\\":0,\\\"hcl\\\":0,\\\"hf\\\":0,\\\"ch2o\\\":0,\\\"sf6\\\":0,\\\"no\\\":0,\\\"h2\\\":0}\",\"video_size\":null,\"wifi_info\":null,\"location\":\"\",\"month_used_video_size\":\"115086\",\"month_max_video_size\":\"20971520\",\"obstacle_distance_up\":\"\",\"obstacle_distance_rear\":\"\",\"sipphone\":\"0\",\"mz_call\":\"0\",\"light_value\":\"0\",\"auto_change_quality\":\"0\",\"last_rail_status\":\"0\"},\"x_point\":\"41.80419297960069\",\"y_point\":\"123.33912543402778\",\"sos_type\":\"1\",\"time\":1758190067,\"msg\":\"\"}";

    @Autowired
    private MapApi mapApi;

    @Autowired
    private AppEmpDataManager appEmpDataManager;

    @Autowired
    private HelmetProperties helmetProperties;

    /**
     * 解析接收的报文
     * @param masage
     */
    public void parseMassage(String masage){
        JSONObject jsonObject = JSONObject.parseObject(masage);
        String cmd = jsonObject.getString("cmd");
        String status = jsonObject.getString("status");
        if (cmd==null||"false".equals(status)) {
            logger.info("指令解析失败cmd={},status={}",cmd,status);
            return;
        }
        switch (cmd){
            case cmd_active_devices:
//                jsonObject = JSONObject.parseObject(mock_data_get_active_devices);
//                logger.info("data string ={}",jsonObject.toJSONString());
                setHelmetData(jsonObject);
                break;
            case cmd_push_sos:
                setWarnData(jsonObject);
                break;
            case cmd_login:
                logger.info("=======登录成功发送获取数据命令=========");
                zbznVideoApi.getDeviceInfo();
                break;
            default:
                break;
        }
    }

    private void setHelmetData(JSONObject jsonObject) {
        logger.info("解析安全帽实时数据:{}", jsonObject.getString("data"));
        JSONArray dataArray = jsonObject.getJSONArray("data");
        for (Object data : dataArray) {
            JSONObject json = JSONObject.parseObject(data.toString());
            JSONObject user_info = json.getJSONObject("user_info");
            String deviceCode = user_info.getString("device_id");
            String capType = user_info.getString("cap_type");
            // 根据code 查询 设备id
            AppDeviceDTO deviceBySn = null;
            if (StringUtils.isEmpty(capType)){
                logger.error("未知设备类型 device_id:{}, capType:{}", deviceCode, capType);
                return;
            }
            JSONObject location_info = json.getJSONObject("location_info");
            // 时间
            String dateString = user_info.getString("c_time");
            // 经度
            String longitude = location_info.getString("y_point");
            // 纬度
            String latitude = location_info.getString("x_point");
            // 电池容量
            Integer batteryLevel = location_info.getInteger("bat_l");
            Double speed = location_info.getDouble("c_speed");
            Integer deviceType = DeviceType.helmet.getValue();
            if (capType.equals("7") || capType.equals("11")){
                deviceType = DeviceType.mach.getValue();
            }
            try {
                deviceBySn = appDeviceService.getDeviceBySnAndType(deviceCode, deviceType);
            } catch (Exception e) {
                logger.error("获取到安全帽硬件异常：{}", deviceCode);
            }
            if (deviceBySn == null) {
                logger.info("注册安全帽硬件:{},", deviceCode);
                int ret = appDeviceService.rigisterDevice(deviceType, deviceCode, deviceCode, capType);
                if (ret > 0) {
                    logger.info("注册成功：{}, ret:{}", deviceCode, ret);
                    deviceBySn = appDeviceService.getDeviceBySnAndType(deviceCode, deviceType);
                } else {
                    logger.info("注册失败：{}", deviceCode);
                    continue;
                }
            }
            if (capType.equals("7") || capType.equals("11")){
                JSONObject marchApp = new JSONObject();
                marchApp.put("deviceId", deviceBySn.getId());
                marchApp.put("deviceCode", deviceCode);
                marchApp.put("batteryPower", batteryLevel);
                marchApp.put("batteryState", 1);
                marchApp.put("deviceTemp", 31);
                marchApp.put("rotationX", 0);
                marchApp.put("rotationY", 0);
                marchApp.put("rotationZ", 0);
                marchApp.put("latWgs84", Double.parseDouble(longitude));
                marchApp.put("lngWgs84", Double.parseDouble(latitude));
                marchApp.put("speed", speed);
                // 构建 workStates 数组
                JSONArray workStatesArray = new JSONArray();
                JSONObject state = new JSONObject();
                state.put("time", new Date());
                state.put("workState", 1);
                // 添加三个相同的状态对象
                workStatesArray.add(state);
                marchApp.put("workStates", workStatesArray);
                amqpTemplate.convertAndSend(QueueConst.MACH_DATA, JSONUtil.toString(marchApp));
            } else {
                // 设备定位数据上传
                CncitUpMsgS reqMsg = new CncitUpMsgS();
                reqMsg.setDeviceId(deviceBySn.getId());
                reqMsg.setTime(new Date(Long.parseLong(dateString) * 1000));
                reqMsg.setLngWgs84(Double.parseDouble(longitude));
                reqMsg.setLatWgs84(Double.parseDouble(latitude));
                reqMsg.setBatteryPower(batteryLevel);
                logger.info("MQ send 安全帽实时数据:{}", JSONUtil.toString(reqMsg));
//            amqpTemplate.convertAndSend(QueueConst.EMP_HELMET_DATA, JSONUtil.toString(reqMsg));

//            CncitUpMsgS reqMsg = JSONObject.parseObject(msg, CncitUpMsgS.class);

                //移除坐标系转换 高德转GPS
//            Gps gcj02Gps = mapApi.translateToGcj02(reqMsg.getLngWgs84(), reqMsg.getLatWgs84());
//            Double lat = gcj02Gps.getLat();
//            Double lng = gcj02Gps.getLng();

                AppDeviceCardLog cardLog = new AppDeviceCardLog();
                BeanUtils.copyProperties(reqMsg, cardLog);
//            cardLog.setLng(lng);
//            cardLog.setLat(lat);
//            MapLoc loc = mapApi.geocode(lng, lat);
                Double lat = reqMsg.getLatWgs84();  // 直接使用原始纬度
                Double lng = reqMsg.getLngWgs84();  // 直接使用原始经度
                cardLog.setLng(lng);
                cardLog.setLat(lat);
                MapLoc loc = mapApi.geocode(lng, lat);
                cardLog.setLocation(loc.getAddress());
                cardLog.setPosState(PosState.VALID.getValue());
                appEmpDataManager.addHelmetData(cardLog);
            }
        }
    }


    private void setWarnData(JSONObject jsonObject) {
        logger.info("接受安全帽报警数据：{}",jsonObject);
        JSONObject data = jsonObject.getJSONObject("data");
        String extra_info = jsonObject.getString("extra_info");
        String device_id = data.getString("device_id");
        String capType = data.getString("cap_type");
        if (StringUtils.isEmpty(capType)){
            logger.error("未知设备类型 device_id:{}, capType:{}", device_id, capType);
            return;
        }
        // 根据code 查询 设备id
        AppDeviceDTO deviceBySn = appDeviceService.getDeviceBySnAndType(device_id, DeviceType.helmet.getValue());
        if (deviceBySn == null) {
            logger.info("未获取到安全帽硬件:{}", device_id);
            return;
        }
        // 经度
        String longitude = jsonObject.getString("y_point");
        // 纬度
        String latitude = jsonObject.getString("x_point");
        // 时间
        String dateString = jsonObject.getString("time");
        if (capType.equals("7") || capType.equals("11")){
//            logger.debug("发送设备报警检测数据到队列,machInfo:{},lastLog:{}", machInfo.toString(), lastLog.toString());
//            MachWarnCheckDTO data = new MachWarnCheckDTO();
//            Integer deptId = machInfo.getHoldDeptId();
//            Integer machId = machInfo.getMachId();
//            data.setTriggerTime(lastLog.getTime());
//            data.setLat(lastLog.getLat());
//            data.setLng(lastLog.getLng());
//            data.setSpeed(lastLog.getSpeed());
//            data.setWorkState(lastLog.getWorkState());
//            data.setMachId(machId);
//            data.setDeptId(deptId);
//            data.setMachCode(machInfo.getMachCode());
//            data.setMachType(machInfo.getMachType());
//            data.setMachTypeName(machInfo.getMachTypeName());
//            data.setMachModelName(machInfo.getMachModelName());
//            data.setTimes(machInfo.getTimes());
//            amqpTemplate.convertAndSend(QueueConst.ALARM_CHECK_DATA, JSONUtil.toString(data));
        } else {
            AppDeviceCardLog log = new AppDeviceCardLog();
            log.setDeviceId(deviceBySn.getId());
            log.setLngWgs84(Double.parseDouble(longitude));
            log.setLng(Double.parseDouble(longitude));
            log.setLatWgs84(Double.parseDouble(latitude));
            log.setLat(Double.parseDouble(latitude));
            log.setTime(new Date(Long.parseLong(dateString) * 1000));
            String sosType = jsonObject.getString("sos_type");
            if (StringUtils.isEmpty(sosType)) {
                return;
            } else if ("0".equals(sosType) || "7".equals(sosType)) { //sos报警
                log.setAlarmSos(1);
            } else if ("1".equals(sosType)) { //脱帽报警
                log.setAlarmDoff(1);
            } else if ("2".equals(sosType)) { //围栏报警
                log.setFence(1);
            } else if ("4".equals(sosType)) { //跌落报警
                log.setAlarmDrop(1);
            } else if ("6".equals(sosType)) { //静默报警/长时间静止报警
                log.setAlarmStill(1);
            }else if ("37".equals(sosType)) { //异常离开工作区域报警
                log.setLeaveStill(1);
            }
            log.setExtraInfo(extra_info);
            appHelmetService.checkWarn(log);
        }

    }

    public void login() {
        zbznVideoApi.login();
    }

    public void getDeviceInfo() {
        zbznVideoApi.getDeviceInfo();
    }
}